package com.fjec.base.shiro;

import com.fjec.common.enums.EnumLoginType;
import com.fjec.common.shiro.AccountInfo;
import com.fjec.common.shiro.MyUserToken;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class NameAndPwdRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // AuthenticatingRealm
        System.out.println("MyRealm1.getAuthenticationInfo");
        String username = (String) token.getPrincipal();  //得到用户名
        String password = new String((char[]) token.getCredentials()); //得到密码
        if (!"zhang".equals(username)) {
            throw new UnknownAccountException(); //如果用户名错误
        }
        if (!"123".equals(password)) {
            throw new IncorrectCredentialsException(); //如果密码错误
        }
//        AccountInfo.init(1000L, username, null, 0);
        //如果身份认证验证成功，返回一个AuthenticationInfo实现；
        return new SimpleAuthenticationInfo(username, password, getName());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        MyUserToken loginToken = (MyUserToken) token;
        if (loginToken.getLoginType() == EnumLoginType.ACCOUNT_PWD) {
            return true;
        } else {
            return false;
        }
    }
}
